<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>我的成绩 - 教学管理系统</title>
    <style>
        body {
            font-family: 'Microsoft YaHei', sans-serif;
            background-color: #f5f5f5;
            margin: 0;
            padding: 0;
        }

        .container {
            display: flex;
            min-height: 100vh;
        }

        .sidebar {
            width: 250px;
            background-color: #2c3e50;
            color: white;
            padding-top: 20px;
        }

        .sidebar-header {
            padding: 0 20px 20px;
            border-bottom: 1px solid #3c5166;
        }

        .sidebar-header h2 {
            margin: 0;
            font-size: 20px;
        }

        .user-info {
            margin-top: 10px;
            font-size: 14px;
            opacity: 0.8;
        }

        .menu {
            list-style: none;
            padding: 0;
            margin: 20px 0;
        }

        .menu li {
            padding: 12px 20px;
            cursor: pointer;
            transition: background-color 0.3s;
        }

        .menu li:hover {
            background-color: #3c5166;
        }

        .menu li.active {
            background-color: #3498db;
        }

        .menu a {
            color: white;
            text-decoration: none;
            display: block;
        }

        .content {
            flex: 1;
            padding: 20px;
        }

        .content-header {
            margin-bottom: 30px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .content-header h1 {
            margin: 0;
            color: #333;
            font-size: 24px;
        }

        .filter-container {
            display: flex;
            gap: 15px;
        }

        .filter-container select {
            padding: 8px 12px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 14px;
        }

        .grade-summary {
            background-color: white;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
            padding: 20px;
            margin-bottom: 30px;
        }

        .summary-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
            gap: 20px;
        }

        .summary-item {
            text-align: center;
        }

        .summary-title {
            font-size: 14px;
            color: #666;
            margin-bottom: 8px;
        }

        .summary-value {
            font-size: 24px;
            font-weight: bold;
            color: #2c3e50;
        }

        .summary-value.excellent {
            color: #27ae60;
        }

        .summary-value.good {
            color: #3498db;
        }

        .summary-value.average {
            color: #f39c12;
        }

        .summary-value.poor {
            color: #e74c3c;
        }

        .grades-container {
            background-color: white;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
            padding: 20px;
            margin-bottom: 20px;
        }

        .grades-container h2 {
            margin-top: 0;
            color: #333;
            font-size: 18px;
            margin-bottom: 20px;
        }

        table {
            width: 100%;
            border-collapse: collapse;
        }

        table th,
        table td {
            padding: 12px 15px;
            text-align: left;
            border-bottom: 1px solid #eee;
        }

        table th {
            background-color: #f8f9fa;
            color: #333;
            font-weight: 600;
        }

        table tr:hover {
            background-color: #f5f5f5;
        }

        .score {
            font-weight: 600;
        }

        .score.excellent {
            color: #27ae60;
        }

        .score.good {
            color: #3498db;
        }

        .score.average {
            color: #f39c12;
        }

        .score.poor {
            color: #e74c3c;
        }

        .empty-grades {
            text-align: center;
            padding: 30px;
            color: #777;
        }

        .logout {
            margin-top: auto;
            padding: 20px;
        }

        .logout a {
            color: #e74c3c;
            text-decoration: none;
        }
    </style>
</head>

<body>
    <div class="container">
        <div class="sidebar">
            <div class="sidebar-header">
                <h2>教学管理系统</h2>
                <div class="user-info" th:if="${session.user}">
                    <span id="sidebar-student-name">学生</span> - <span th:text="${session.user.role}">学生</span>
                </div>
            </div>
            <ul class="menu">
                <li><a href="/student/dashboard">我的概览</a></li>
                <li><a href="/student/courses">选课中心</a></li>
                <li><a href="/student/schedule">我的课表</a></li>
                <li class="active"><a href="/student/grades">我的成绩</a></li>
                <li><a href="/student/profile">个人信息</a></li>
            </ul>
            <div class="logout">
                <a href="/logout">退出登录</a>
            </div>
        </div>

        <div class="content">
            <div class="content-header">
                <h1>我的成绩单</h1>
                <div class="filter-container">
                    <select id="semesterFilter" onchange="filterGrades()">
                        <option value="all">所有学期</option>
                        <option value="大一上">大一上</option>
                        <option value="大一下">大一下</option>
                        <option value="大二上">大二上</option>
                        <option value="大二下">大二下</option>
                        <option value="大三上">大三上</option>
                        <option value="大三下">大三下</option>
                        <option value="大四上">大四上</option>
                        <option value="大四下">大四下</option>
                    </select>
                    <select id="courseTypeFilter" onchange="filterGrades()">
                        <option value="all">所有课程类型</option>
                        <option value="必修课">必修课</option>
                        <option value="选修课">选修课</option>
                        <option value="公选课">公选课</option>
                    </select>
                </div>
            </div>

            <div class="grade-summary">
                <div class="summary-grid">
                    <div class="summary-item">
                        <div class="summary-title">课程总数</div>
                        <div class="summary-value" id="totalCourses">0</div>
                    </div>
                    <div class="summary-item">
                        <div class="summary-title">已修课程数</div>
                        <div class="summary-value" id="completedCourses">0</div>
                    </div>
                    <div class="summary-item">
                        <div class="summary-title">总学分</div>
                        <div class="summary-value" id="totalCredit">0</div>
                    </div>
                    <div class="summary-item">
                        <div class="summary-title">平均成绩</div>
                        <div class="summary-value" id="avgScore">-</div>
                    </div>
                    <div class="summary-item">
                        <div class="summary-title">最高成绩</div>
                        <div class="summary-value excellent" id="highestScore">-</div>
                    </div>
                    <div class="summary-item">
                        <div class="summary-title">最低成绩</div>
                        <div class="summary-value poor" id="lowestScore">-</div>
                    </div>
                </div>
            </div>

            <div class="grades-container">
                <h2>成绩详情</h2>
                <table>
                    <thead>
                        <tr>
                            <th>课程编号</th>
                            <th>课程名称</th>
                            <th>课程类型</th>
                            <th>学分</th>
                            <th>修读学期</th>
                            <th>状态</th>
                            <th>成绩</th>
                        </tr>
                    </thead>
                    <tbody id="gradesTableBody">
                        <!-- 成绩数据将通过JavaScript动态加载 -->
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <script>
        // 页面加载时获取成绩数据
        document.addEventListener('DOMContentLoaded', function () {
            fetchStudentInfo();
            fetchGrades();
        });

        // 获取学生信息
        function fetchStudentInfo() {
            fetch('/api/student/info')
                .then(response => {
                    if (!response.ok) {
                        if (response.status === 401) {
                            alert('未授权，请重新登录');
                            window.location.href = '/login';
                            throw new Error('未授权');
                        }
                        return response.text().then(text => { throw new Error(text || '获取学生信息失败') });
                    }
                    return response.json();
                })
                .then(student => {
                    // 更新侧边栏显示的学生姓名
                    document.getElementById('sidebar-student-name').textContent = student.name;
                })
                .catch(error => {
                    console.error('获取学生信息出错:', error);
                });
        }

        // 获取成绩数据
        function fetchGrades() {
            fetch('/api/student/grades')
                .then(response => {
                    if (!response.ok) {
                        if (response.status === 401) {
                            alert('未授权，请重新登录');
                            window.location.href = '/login';
                            throw new Error('未授权');
                        }
                        return response.text().then(text => { throw new Error(text || '获取成绩失败') });
                    }
                    return response.json();
                })
                .then(gradesData => {
                    // 存储完整的成绩数据
                    window.allGrades = gradesData;

                    // 计算统计数据并更新摘要
                    updateGradeSummary(gradesData);

                    // 渲染成绩表格
                    renderGradesTable(gradesData);
                })
                .catch(error => {
                    console.error('获取成绩失败:', error);
                    alert('获取成绩失败: ' + error.message);
                });
        }

        // 更新成绩摘要
        function updateGradeSummary(gradesData) {
            const totalCourses = gradesData.length;
            const completedCourses = gradesData.filter(grade => grade.status === '已修').length;

            // 计算总学分
            const totalCredit = gradesData.reduce((sum, grade) => {
                return sum + (grade.credit || 0);
            }, 0);

            // 计算平均成绩、最高分和最低分
            const coursesWithScores = gradesData.filter(grade => grade.score !== null && grade.status === '已修');

            let avgScore = '-';
            let highestScore = '-';
            let lowestScore = '-';

            if (coursesWithScores.length > 0) {
                const scores = coursesWithScores.map(grade => parseFloat(grade.score));
                const totalScore = scores.reduce((sum, score) => sum + score, 0);
                avgScore = (totalScore / scores.length).toFixed(1);
                highestScore = Math.max(...scores).toFixed(1);
                lowestScore = Math.min(...scores).toFixed(1);
            }

            // 更新DOM
            document.getElementById('totalCourses').textContent = totalCourses;
            document.getElementById('completedCourses').textContent = completedCourses;
            document.getElementById('totalCredit').textContent = totalCredit;
            document.getElementById('avgScore').textContent = avgScore;
            document.getElementById('highestScore').textContent = highestScore;
            document.getElementById('lowestScore').textContent = lowestScore;

            // 根据平均分设置样式
            const avgScoreElement = document.getElementById('avgScore');
            if (avgScore !== '-') {
                const score = parseFloat(avgScore);
                if (score >= 90) {
                    avgScoreElement.className = 'summary-value excellent';
                } else if (score >= 80) {
                    avgScoreElement.className = 'summary-value good';
                } else if (score >= 70) {
                    avgScoreElement.className = 'summary-value average';
                } else {
                    avgScoreElement.className = 'summary-value poor';
                }
            }
        }

        // 渲染成绩表格
        function renderGradesTable(gradesData) {
            const tableBody = document.getElementById('gradesTableBody');
            tableBody.innerHTML = '';

            if (gradesData.length === 0) {
                const emptyRow = document.createElement('tr');
                emptyRow.innerHTML = '<td colspan="7" class="empty-grades">暂无成绩记录</td>';
                tableBody.appendChild(emptyRow);
                return;
            }

            // 按学期逆序排序（最近的学期在前）
            const semesterOrder = {
                '大一上': 1, '大一下': 2,
                '大二上': 3, '大二下': 4,
                '大三上': 5, '大三下': 6,
                '大四上': 7, '大四下': 8
            };

            gradesData.sort((a, b) => {
                const yearDiff = b.year - a.year;
                if (yearDiff !== 0) return yearDiff;
                return semesterOrder[b.semester] - semesterOrder[a.semester];
            });

            gradesData.forEach(grade => {
                const row = document.createElement('tr');

                // 设置成绩样式
                let scoreClass = '';
                let scoreDisplay = '-';

                if (grade.score !== null) {
                    const score = parseFloat(grade.score);
                    scoreDisplay = score.toFixed(1);

                    if (score >= 90) {
                        scoreClass = 'excellent';
                    } else if (score >= 80) {
                        scoreClass = 'good';
                    } else if (score >= 70) {
                        scoreClass = 'average';
                    } else {
                        scoreClass = 'poor';
                    }
                }

                row.innerHTML = `
                    <td>${grade.courseId}</td>
                    <td>${grade.courseName}</td>
                    <td>${grade.courseType || '-'}</td>
                    <td>${grade.credit || '-'}</td>
                    <td>${grade.semester} (${grade.year})</td>
                    <td>${grade.status}</td>
                    <td><span class="score ${scoreClass}">${scoreDisplay}</span></td>
                `;

                tableBody.appendChild(row);
            });
        }

        // 根据筛选条件过滤成绩
        function filterGrades() {
            const semesterFilter = document.getElementById('semesterFilter').value;
            const courseTypeFilter = document.getElementById('courseTypeFilter').value;

            if (!window.allGrades) return;

            let filteredGrades = window.allGrades;

            // 按学期筛选
            if (semesterFilter !== 'all') {
                filteredGrades = filteredGrades.filter(grade => grade.semester === semesterFilter);
            }

            // 按课程类型筛选
            if (courseTypeFilter !== 'all') {
                filteredGrades = filteredGrades.filter(grade => grade.courseType === courseTypeFilter);
            }

            // 更新表格和统计数据
            updateGradeSummary(filteredGrades);
            renderGradesTable(filteredGrades);
        }
    </script>
</body>

</html>